// var mock = require('../../mock/addrPicker');
var Promise = require('../../utils/promise.js');
var modal = require('../../utils/modal');
var request = require('../../utils/request');
var regionArr = [];//存放的是数组形式的省市区
var Promise = require('../../utils/promise');
var utils = require('../../utils/utils');

var that;

function getRegionData() {
    return new Promise((resolve, reject) => {
        wx.request({
            url: 'https://mat1.gtimg.com/city/youpin/data/address-v1.json',
            headers: {
                'Content-Type': 'application/json'
            },
            success: function(res) {
                var _regionArr = []
                var _provinceArr = []
                var _provinceIdArr = []
                res.data.data.map(function(prov){
                    var tmp = {
                        name: prov.name,
                        key: prov.id,
                        first_letter: prov.first_letter,
                        city: {}
                    }
                    prov.children.map(function(city){
                        var tmp1 = {
                            name: city.name,
                            area: {}
                        }
                        city.children.map(function(area){
                            tmp1.area[area.id] = {
                                name: area.name
                            }
                        })
                        tmp.city[city.id] = tmp1
                    })
                    _regionArr.push(tmp)
                    _provinceArr.push(prov.name)
                    _provinceIdArr.push(prov.id)
                })
                resolve({
                    regionArr: _regionArr,
                    provinceArr: _provinceArr,
                    provinceIdArr: _provinceIdArr
                })
            },
            fail: function(res) {
                reject(res)
            }
        }) 
    });
}

module.exports = {
    data:{
        wiiAddrPicker:{
            list:[],
            showList:false,
            addr:{},
            showAddr:false,
            regionArr: [],
            selectedData:{},
            provinceArr:[],
            provinceIdArr: [],
            selectedProvince:'请选择省份',
            provinceIndex:0,
            cityArr:[],
            cityIdArr:[],
            cityObj:{},
            cityObjArr:[],
            selectedCity:'请选择城市',
            cityIndex:0,
            areaArr:[],
            areaIdArr:[],
            areaObjArr:[],
            selectedArea:'请选择区域',
            areaIndex:0,
            listLength:1,
            scrollHeight:''
        }
    },
    onLoad: function() {
        that = this;
        getRegionData().then((data) => {
            that.setData({
                'wiiAddrPicker.provinceArr': data.provinceArr,
                'wiiAddrPicker.regionArr': data.regionArr,
                'wiiAddrPicker.provinceIdArr': data.provinceIdArr
            })
        })
    },
    wiiAddrPickerGetDefaultAddr:function(cfg,callback){
        var addrPickerUrl = this.data.wiiAddrPicker.addrPickerUrl;
        var getListKey = this.data.wiiAddrPicker.addrPickerKey.getAddrList;
        var data = {
            [getListKey]:{}
        };
        var addrListData;
        var addrPickerUrl = this.data.wiiAddrPicker.addrPickerUrl;
        var addAddrKey = this.data.wiiAddrPicker.addrPickerKey.addAddr;
        var getCityInfoKey = this.data.wiiAddrPicker.addrPickerKey.getCityInfo;
        var addrPromise = function(res){
            return new Promise((resolve,reject)=>{
                modal.hide();
                var resData = res[getListKey];
                if(!resData.ret){
                    addrListData = resData.data;
                    var listLength = addrListData.length;
                    if(listLength == 0){
                        if(cfg.wiiAddrPickerUseWxAddr && wx.chooseAddress){
                            wx.chooseAddress({
                                success:function(res){
                                    var data = {
                                        addr:res.detailInfo,
                                        real_name:res.userName,
                                        mobile:res.telNumber

                                    }
                                    request.post({path:addrPickerUrl},{[getCityInfoKey]:{
                                        code: res.nationalCode,
                                        parent_level: 1
                                    }}).then(function(res){
                                        res = res[getCityInfoKey];
                                        if(res.ret == 0 && res.data) {
                                            data.province_id = res.data.parent[0].parent[0].id; // 省id
                                            data.city_id = res.data.parent[0].id; // 市id
                                            data.area = res.data.id; // 区id

                                            if(data.province_id && data.city_id && data.area) {
                                                request.post({path:addrPickerUrl},{[addAddrKey]:data}).then(function(res){
                                                    var resData = res[addAddrKey];
                                                    if(!resData.ret){
                                                        modal.toast('新增成功')
                                                        var addrObj = resData.data;
                                                        callback(addrObj);
                                                        wiiAddrPickerTemp.list.push(addrObj);
                                                        _this.wiiAddrPickerGetAddrList(wiiAddrPickerTemp.list);
                                                    }else{
                                                        modal.toast(resData.msg || '操作失败');
                                                    }
                                                });
                                            }
                                            else{
                                                callback()
                                            }
                                        }
                                        else{
                                            modal.confirm('提示', res.msg);
                                            callback()
                                        }
                                    });
                                },
                                fail:function(res){
                                    modal.confirm('','您拒绝访问微信的地址通信录！')
                                },
                                complete:function(res){

                                }
                            });
                        }else{
                            callback()
                        }
                    }else{
                        var tempNum = 0;
                        for(var i=0;i<listLength;i++){
                            if(addrListData[i].default == 1){
                                tempNum = i;
                            }
                        }
                        var defaultAddr = addrListData[tempNum];
                        callback(defaultAddr);
                    }
                }else{
                    modal.toast(res.msg)
                } 
            })
            
        }
        request.post({path:addrPickerUrl},data).then(function(data){
            addrPromise(data);
        });
    },
    wiiAddrPickerAddAddr:function(){
        modal.loading('加载中',200000);
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        var addrTemp = {
            'addr':'',
            'real_name':'',
            'mobile':'',
            'default':'0'
        };
        this.setData({
            'wiiAddrPicker.showAddr':true,
            'wiiAddrPicker.addr':addrTemp,
            'wiiAddrPicker.selectedData':{},
            'wiiAddrPicker.selectedProvince':'请选择省份',
            'wiiAddrPicker.selectedCity':'请选择城市',
            'wiiAddrPicker.selectedArea':'请选择区域'
            // 'wiiAddrPicker.provinceArr':provinceArr,
            // 'wiiAddrPicker.regionArr':regionArr
        });
        modal.hide();
    },
    wiiAddrPickerEditAddr:function(evt){
        modal.loading('加载中',200000);
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        var regionArr = wiiAddrPickerTemp.regionArr;
        var id = evt.currentTarget.dataset.id;
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        var addr;
        wiiAddrPickerTemp.list.forEach(function(value){
            if(value.id == id){
                addr = value;
            }
        });
        var provinceIndexTemp = that.data.wiiAddrPicker.provinceIdArr.indexOf(addr.province_id);
        if(provinceIndexTemp == -1){
            provinceIndexTemp = null;
            addr.province_name = '请选择省份';
        }
        var cityIndexTemp,areaIndexTemp;

        // 因getCityData和wiiAddrPickerGetAreaData会更新data数据，故此处不能使用wiiAddrPicerTemp缓存数据
        this.wiiAddrPickerGetCityData(provinceIndexTemp);
        cityIndexTemp = this.data.wiiAddrPicker.cityIdArr.indexOf(addr.city_id);
        if(cityIndexTemp == -1){
            cityIndexTemp = null;
            addr.city_name = '请选择城市';
        }
        this.wiiAddrPickerGetAreaData(cityIndexTemp);
        areaIndexTemp = this.data.wiiAddrPicker.areaIdArr.indexOf(addr.area);
        if(areaIndexTemp == -1){
            areaIndexTemp = null;
            addr.area_name = '请选择区域';
        }
        var selectedDataTemp = {
            province_name:addr.province_name,
            province_id:addr.province_id,
            city_name:addr.city_name,
            city_id:addr.city_id,
            area_name:addr.area_name,
            area:addr.area

        };

        var currentAddrIndex = this.wiiAddrPickerGetAddrIndex(id);        
        this.setData({
            'wiiAddrPicker.showAddr':true,
            'wiiAddrPicker.addr':this.data.wiiAddrPicker.list[currentAddrIndex],
            'wiiAddrPicker.selectedProvince':addr.province_name,
            'wiiAddrPicker.provinceIndex':provinceIndexTemp,
            'wiiAddrPicker.selectedCity':addr.city_name,
            'wiiAddrPicker.cityIndex':cityIndexTemp,
            'wiiAddrPicker.selectedArea':addr.area_name,
            'wiiAddrPicker.areaIndex':areaIndexTemp,
            'wiiAddrPicker.selectedData':selectedDataTemp
            // 'wiiAddrPicker.provinceArr':provinceArr,
            // 'wiiAddrPicker.regionArr':regionArr
        });
        modal.hide();
    },
    wiiAddrPickerInitRegion:function(){
        // var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        // for(var id in regionJson){
        //     regionJson[id]['key'] = id;
        //     regionArr.push(regionJson[id]);
        //     provinceArrTemp.push(regionJson[id]['name'])
        // }
    },
    wiiAddrPickerGetAddrIndex:function(id){
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        var currentIndex = '';
        wiiAddrPickerTemp.list.forEach(function(value){
            if(value.id == id){
                currentIndex = wiiAddrPickerTemp.list.indexOf(value); 
            }
        });
        return currentIndex;
    },
    wiiAddrPickerSetDefault:function(e){
        var _this = this;
        var id = e.currentTarget.dataset.id;
        var addrPickerUrl = this.data.wiiAddrPicker.addrPickerUrl;
        var setDefaultKey = this.data.wiiAddrPicker.addrPickerKey.setDefault;
        var data = {
            [setDefaultKey]:{
                "adr_id":id
            }
        };
        request.post({path:addrPickerUrl},data).then(function(res){
            var resData = res[setDefaultKey];
            if(!resData.ret){
                var wiiAddrPickerTemp = _this.data.wiiAddrPicker;
                var addrList = wiiAddrPickerTemp.list;
                addrList.forEach(function(value){
                    if(value.id == id){
                        value.default = '1';
                    }else{
                        value.default = '0';
                    }
                });
                _this.wiiAddrPickerGetAddrList(wiiAddrPickerTemp.list);
            }else{
                console.log(resData.msg)
            }
        });
        
    },
    wiiAddrPickerDeleteAddr:function(e){
        var _this = this;
        var id = e.currentTarget.dataset.id;
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        var addrPickerUrl = this.data.wiiAddrPicker.addrPickerUrl;
        var delAddrKey = this.data.wiiAddrPicker.addrPickerKey.delAddr;
        modal.confirm('您确定删除该地址?','',function(res){
            if(res){
                // todo 调删除接口   
                var data = {
                    [delAddrKey]:{
                        "adr_id":id
                    }
                };
                request.post({path:addrPickerUrl},data).then(function(res){
                    var resData = res[delAddrKey];
                    if(!resData.ret){
                        modal.toast('删除成功');
                        var currentIndex = _this.wiiAddrPickerGetAddrIndex(id);
                        wiiAddrPickerTemp.list.splice(currentIndex,1);
                        _this.wiiAddrPickerGetAddrList(wiiAddrPickerTemp.list);
                    }
                });
               
            }
        });
    },
    wiiAddrPickerSelectAddr:function(){
        this.setData({
            'wiiAddrPicker.showList':true,
            'wiiAddrPicker.tapAddr':'wiiAddrPickerTapAddr'
        });
        this.wiiAddrPickerGetAddrList();
    },
    wiiAddrPickerTapAddr:function(e){
        var id = e.currentTarget.dataset.id;
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        var currentIndex = this.wiiAddrPickerGetAddrIndex(id);
        var addrData = wiiAddrPickerTemp.list[currentIndex];

        this.callback.call(this,'addrPicker',utils.assign({}, addrData));
        wiiAddrPickerTemp.list[currentIndex].edit = false; // 取消编辑状态
        this.setData({
            'wiiAddrPicker.showList':false,
            'wiiAddrPicker.list':wiiAddrPickerTemp.list, 
            'wiiAddrPicker.addr':wiiAddrPickerTemp.list[currentIndex]
        });
    },
    wiiAddrPickerShowAddrList:function(){
        this.setData({
            'wiiAddrPicker.showList':true,
            'wiiAddrPicker.tapAddr':''
        })
        this.wiiAddrPickerGetAddrList();
    },
    wiiAddrPickerGetAddrList:function(dataList){
        var _this = this;
        var addrPickerUrl = this.data.wiiAddrPicker.addrPickerUrl;
        var getListKey = this.data.wiiAddrPicker.addrPickerKey.getAddrList;
        var data = {
            [getListKey]:{}
        };
        var addrListData;
        var scrollHeight;
        var solidHeight = 84+10;
        wx.getSystemInfo({
            success: function(res) {
                var screenHight = res.windowHeight;
                scrollHeight = screenHight - solidHeight;
                if(!!dataList){
                    addrListData = dataList;
                    var listLength = addrListData.length;
                    _this.setData({
                        'wiiAddrPicker.list':addrListData,
                        'wiiAddrPicker.listLength':listLength,
                        'wiiAddrPicker.showAddr':false,
                        'wiiAddrPicker.scrollHeight':scrollHeight+'px'
                    });
                }else{
                    modal.loading('数据加载中');
                    var addrPromise = function(res){
                        return new Promise((resolve,reject)=>{
                            modal.hide();
                            var resData = res[getListKey];
                            if(!resData.ret){
                                addrListData = resData.data;

                                var listLength = addrListData.length>0 ? true : false;
                                _this.setData({
                                    'wiiAddrPicker.list':addrListData,
                                    'wiiAddrPicker.listLength':listLength,
                                    'wiiAddrPicker.showAddr':false,
                                    'wiiAddrPicker.scrollHeight':scrollHeight+'px'
                                });
                            }else{
                                modal.toast(res.msg)
                            } 
                        })
                        
                    }
                    request.post({path:addrPickerUrl},data).then(function(data){
                        addrPromise(data);
                    });
                }
            }
        });
    },
    wiiAddrPickerGoHomePage:function(){
        modal.loading('加载中',200000);
        console.log('你点中了返回按钮');
        this.setData({
            'wiiAddrPicker.showList':false,
            'wiiAddrPicker.showAddr':false
        });
        modal.hide();
    },
    wiiAddrPickerGoListPage:function(){
        modal.loading('加载中',200000);
        console.log('你点中了返回按钮');
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        this.setData({
            'wiiAddrPicker.addr':{}
        })
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        this.wiiAddrPickerGetAddrList(wiiAddrPickerTemp.list);
        modal.hide();
    },
    changeRadio:function(e){
        console.log('radio发生change事件，携带value值为：', e.detail.value)
    },
    wiiAddrPickerGetCityData:function(index){
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        if(index == null){
            return;
        }
        var cityObj = wiiAddrPickerTemp.regionArr[index]['city'];
        var cityArrTemp = [];
        var cityIdArrTemp = [];
        var cityObjArrTemp = [];

        for(var key in cityObj){
            cityObj[key]['key'] = key;
            cityArrTemp.push(cityObj[key]['name']);
            cityIdArrTemp.push(cityObj[key]['key']);
            cityObjArrTemp.push(cityObj[key]);
        }

        this.setData({
            'wiiAddrPicker.selectedProvince':wiiAddrPickerTemp.provinceArr[index],
            'wiiAddrPicker.cityArr':cityArrTemp,
            'wiiAddrPicker.cityIdArr':cityIdArrTemp,
            'wiiAddrPicker.cityObj':cityObj,
            'wiiAddrPicker.cityObjArr':cityObjArrTemp
        });
    },
    wiiAddrPickerSeleProvince:function(e){
        var index = e.detail.value;
        if(index == 'null'){
            return;
        }
        this.wiiAddrPickerGetCityData(index);
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        var currentProvince = wiiAddrPickerTemp.regionArr[index];
        this.setData({
            'wiiAddrPicker.provinceIndex':0,
            'wiiAddrPicker.cityIndex':0,
            'wiiAddrPicker.areaIndex':0,
            'wiiAddrPicker.selectedCity':'请选择城市',
            'wiiAddrPicker.selectedArea':'请选择区域',
            'wiiAddrPicker.selectedData.province_id':currentProvince.key,
            'wiiAddrPicker.selectedData.province_name':currentProvince.name
        });
    },
    wiiAddrPickerGetAreaData:function(index){
        if(index == null){
            return;
        }
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        var currentCity = wiiAddrPickerTemp.cityObjArr[index];
        var areaObj = currentCity['area'];
        var areaArrTemp = [];
        var areaIdArrTemp = [];
        var areaObjArrTemp = [];
        for(var key in areaObj){
            areaObj[key]['key'] = key;
            areaArrTemp.push(areaObj[key]['name']);
            areaIdArrTemp.push(areaObj[key]['key']);
            areaObjArrTemp.push(areaObj[key]);
        }
        this.setData({
            'wiiAddrPicker.selectedArea':'请选择区域',
            'wiiAddrPicker.selectedCity':wiiAddrPickerTemp.cityArr[index],
            'wiiAddrPicker.areaArr':areaArrTemp,
            'wiiAddrPicker.areaIdArr':areaIdArrTemp,
            'wiiAddrPicker.areaObjArr':areaObjArrTemp,
            'wiiAddrPicker.selectedData.city_id':currentCity.key,
            'wiiAddrPicker.selectedData.city_name':currentCity.name
        });
    },
    wiiAddrPickerSeleCity:function(e){
        var index = e.detail.value;
        if(index == 'null'||!index.length){
            return;
        }
        this.wiiAddrPickerGetAreaData(index);
    },
    wiiAddrPickerSeleArea:function(e){
        var index = e.detail.value;
        if(index == 'null' || !index.length){
            return;
        }
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        var currentArea = wiiAddrPickerTemp.areaObjArr[index];
        this.setData({
            'wiiAddrPicker.selectedArea':wiiAddrPickerTemp.areaArr[index],
            'wiiAddrPicker.selectedData.area':currentArea.key,
            'wiiAddrPicker.selectedData.area_name':currentArea.name
        });
    },
    wiiAddrPickerSubmitForm:function(evt){
        var _this = this;
        var data = {};
        var form = evt.detail.value;
        var wiiAddrPickerTemp = this.data.wiiAddrPicker;
        var selectedDataTemp = wiiAddrPickerTemp.selectedData;
        var addrPickerUrl = this.data.wiiAddrPicker.addrPickerUrl;
        var addAddrKey = this.data.wiiAddrPicker.addrPickerKey.addAddr;
        // 表单验证
        if(!selectedDataTemp.province_name){
            modal.confirm('请选择省份','');
            return false;
        }
        if(!selectedDataTemp.city_name){
            modal.confirm('请选择城市','');
            return false;
        }
        if(!selectedDataTemp.area_name){
            modal.confirm('请选择区域','');
            return false;
        }
        if(!form.addr){
            modal.confirm('请输入详细地址','');
            return false;
        }
        if(!form.real_name){
            modal.confirm('请输入姓名','');
            return false;   
        }
        if(!form.mobile){
            modal.confirm('请输入电话','');
            return false;   
        }else if(!/^1[3,4,5,7,8]\d{9}$/.test(form.mobile)){
            modal.confirm('请输入正确的11位电话','');
            return false;   
        }
        // 拼接详细地址,后期都有接口返回的值替代
        var addrDetail = '';
        
        if(selectedDataTemp.province_name == selectedDataTemp.city_name){
            addrDetail += selectedDataTemp.province_name+'市'+selectedDataTemp.area_name+'区'+form.addr;
        }else{
            addrDetail += selectedDataTemp.province_name+'省'+selectedDataTemp.city_name+'市'+selectedDataTemp.area_name+'区'+form.addr;
        }
        var detailObj = {final_address:addrDetail};

        // 判断是新增还是编辑页
        if(!!form.id){
            var currentIndex = this.wiiAddrPickerGetAddrIndex(form.id);
            form = utils.assign(form,this.data.wiiAddrPicker.selectedData);
            request.post({path:addrPickerUrl},{[addAddrKey]:form}).then(function(res){
                var resData = res[addAddrKey];
                if(!resData.ret){
                    modal.toast('编辑成功');
                    resData.data.edit = true;
                    var addrObj = utils.assign(wiiAddrPickerTemp.list[currentIndex],resData.data);
                    wiiAddrPickerTemp.list[currentIndex] = addrObj;
                    _this.wiiAddrPickerGetAddrList(wiiAddrPickerTemp.list);
                }else{
                    modal.toast(res.msg);
                }
            });
            
           

        }else{
            form.id = '';
            data = utils.assign(form,_this.data.wiiAddrPicker.selectedData);
            request.post({path:addrPickerUrl},{[addAddrKey]:data}).then(function(res){
                var resData = res[addAddrKey];
                if(!resData.ret){
                    modal.toast('新增成功')
                    var addrObj = resData.data;
                    wiiAddrPickerTemp.list.push(addrObj);
                    _this.wiiAddrPickerGetAddrList(wiiAddrPickerTemp.list);
                }else{
                    modal.toast(res.msg);
                }
            });
        }
        
    }
}